<template>
  <div>
    <div
      style="padding-top: 20px"
      v-if="showSearch"
      :class="{
        'enter-level flipInX': showSearch,
      }"
    >
      <el-form :inline="true" :model="videolistsearch" class="demo-form-inline">
        <el-row :gutter="25" style="margin-left: 0px; margin-right: 0px">
          <el-col :span="5">
            <el-form-item label="广告编号">
              <el-input
                v-model="videolistsearch.id"
                placeholder="请输入广告编号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="标题">
              <el-input
                v-model="videolistsearch.title"
                placeholder="请输入标题"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="提交时间">
              <div class="block">
                <el-date-picker
                  v-model="loginTime"
                  placeholder="-"
                  style="width: 90%"
                  :unlink-panels="true"
                  type="datetimerange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                >
                </el-date-picker>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item style="width: 90%">
              <el-button type="primary" @click="getDataList" :icon="Search">
                搜索
              </el-button>
              <el-button type="info" @click="reset" :icon="Refresh">
                重置
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
        </el-row>
      </el-form>
    </div>
    <div style="padding: 30px">
      <div style="display: flex; justify-content: space-between">
        <div>
          <el-button :icon="Plus" type="success" @click="insert">
            新增
          </el-button>
          <el-button
            :icon="Delete"
            type="danger"
            plain
            @click="removeLog"
            :disabled="isBatch"
            >删除</el-button
          >
        </div>
        <div>
          <el-button
            :icon="Search"
            circle
            @click="showSearch = !showSearch"
          ></el-button>
          <el-button :icon="Refresh" circle @click="reset"></el-button>
        </div>
      </div>
      <el-table
        ref="multipleTableRef"
        :data="dataList"
        style="width: 100%"
        height="600"
        @selection-change="handleSelectionChange"
        v-loading="dataLoding"
      >
        <el-table-column
          align="center"
          type="selection"
          :selectable="selectable"
          width="55"
        />
        <el-table-column property="id" label="广告编号" width="105" />
        <el-table-column #default="scope" label="首图" width="150">
          <el-image :src="scope.row.imgUrl" style="width:100px;height:60px"/>
        </el-table-column>
        <el-table-column property="title" label="标题" />
        <el-table-column property="position" label="位置" />
        <el-table-column property="targetUrl" label="模板路径" />
        <el-table-column #default="scope" label="状态">
          <template v-if="scope.row.status == 0">
            <el-tag type="success">正常</el-tag></template
          >
          <template v-if="scope.row.status == 1"
            ><el-tag type="error">禁用</el-tag></template
          >
        </el-table-column>
        <el-table-column
          #default="scope"
          sortable
          label="提交时间"
          width="205"
          >{{
            tool.formatDateToYYYYMMDD(scope.row.createTime)
          }}</el-table-column
        >
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="确定要删除吗？"
              @confirm="oneremoveLog(scope.row)"
              @cancel="removeCnacle"
            >
              <template #reference>
                <el-button type="text" :icon="Delete"> 删除 </el-button>
              </template>
            </el-popconfirm>
            <el-button
              v-if="scope.row.status == 0"
              @click="toSeting(1, scope.row.id)"
              type="text"
              :icon="Lock"
            >
              禁用
            </el-button>
            <el-button
              v-if="scope.row.status == 1"
              @click="toSeting(0, scope.row.id)"
              type="text"
              :icon="Unlock"
            >
              解禁
            </el-button>
            <el-button @click="toUpdata(scope.row)" type="text" :icon="Edit">
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 10px">
        <el-pagination
          :hide-on-single-page="false"
          background
          layout="prev, pager, next"
          :total="pages.total"
          :page-size="videolistsearch.pageSize"
          :page-count="pages.pages"
          @current-change="changePage"
          :pager-count="15"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogOverflowVisible"
      title="修改广告位置"
      width="400"
      draggable
      overflow
    >
      <el-form-item label="位置">
        <el-select
          v-model="videoposition"
          placeholder="请选择广告位置"
          clearable
        >
          <el-option
            v-for="(index, item) in position"
            :key="index"
            :label="index"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Cancel">取消</el-button>
          <el-button @click="UpdataType">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <ad-add ref="adAddRef" @upload="onUpload"></ad-add>
</template>

<script setup>
import tool from "@/assets/js/tool";
import request from "@/assets/js/request";
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ElLoading } from "element-plus";
import axios from "axios";
import {
  Search,
  Refresh,
  Delete,
  Plus,
  Lock,
  Unlock,
  Edit,
} from "@element-plus/icons-vue";

import adAdd from "@/components/ad/ad-add.vue";

const videolistsearch = ref({
  id: null,
  title: "",
  beginTime: null,
  endTime: null,
  idlist: "",
  pageNum: 1,
  pageSize: 20,
});
const position = ref([
  "弹窗",
  "首页头部",
  "首页底部",
  "分类头部",
  "分类底部",
  "用户中心头部",
  "用户中心底部",
]);
const dataList = ref([]);
const pages = ref({
  total: 0,
  pages: 0,
});
const isSend = ref(0);
const adAddRef = ref();
//修改弹窗
const dialogOverflowVisible = ref(false);
//修改广告位置参数
const videoposition = ref();
//时间区间
const loginTime = ref();
const showSearch = ref(true);
const dataLoding = ref(false);

// 记录当前批量删除tag的步骤
const selectable = ref();
const isBatch = ref(true);
const selectKey = ref([]);

const loading = ref();

//确定idlist
const getIdList = (data) => {
  if (data.length > 0) {
    data.forEach((element) => {
      videolistsearch.value.idlist =
        element + "," + videolistsearch.value.idlist;
    });
  }
};

const insert = () => {
  adAddRef.value.open();
};
//修改弹窗
const toUpdata = (data) => {
  videolistsearch.value.idlist = data.id;
  dialogOverflowVisible.value = true;
};
//禁用---解禁
const toSeting = (key, data) => {
  request
    .post(`/admin/ad/set?id=${data}&status=${key}`)
    .then((res) => {
      if (res.code === 200) {
        getDataList();
      }
    })
    .catch((err) => {
      console.log("错误信息：", err.message);
    });
};
//弹窗取消
const Cancel = () => {
  videoposition.value = null;
  videolistsearch.value.idlist = "";
  dialogOverflowVisible.value = false;
};
//修改确定
const UpdataType = () => {
  console.log("数据是：" + videoposition.value);
  request
    .post(
      `/admin/ad/updata?position=` +
        videoposition.value +
        "&idlist=" +
        videolistsearch.value.idlist
    )
    .then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: "修改成功",
        });
        getDataList();
      }
      Cancel();
    })
    .catch((err) => {
      console.log("错误信息：", err.message);
    });
};

//确定开始和结束时间分开
const separate = (data) => {
  if (data) {
    videolistsearch.value.beginTime = data[0];
    videolistsearch.value.endTime = data[1];
  }
};
//获取数据
const getDataList = () => {
  dataLoding.value = true;
  getIdList(selectKey.value);
  separate(loginTime);
  request
    .post("/admin/ad/page", videolistsearch.value)
    .then((res) => {
      console.log("获取额数据：" + res.data);
      if (res.code === 200) {
        dataList.value = res.data.list;
        pages.value.total = res.data.total;
        pages.value.pages = res.data.pages;
      } else {
        ElMessage.error(res.msg);
      }
      dataLoding.value = false;
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
  setTimeout(() => {
    dataLoding.value = false;
  }, 5000);
};
//换页
const changePage = (pageIndex) => {
  videolistsearch.value.pageNum = pageIndex;
  getDataList();
};
//删除请求
const removeRequest = () => {
  console.log("发送：" + videolistsearch.value.idlist);
  request
    .post(`/admin/ad/del?idlist=` + videolistsearch.value.idlist)
    .then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
      } else {
        ElMessage({
          type: "info",
          message: "删除失败",
        });
      }
      getDataList();
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
  selectKey.value = [];
};
//批量删除事件
const removeLog = () => {
  getIdList(selectKey.value);
  ElMessageBox.confirm("确定删除所选项?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      removeRequest();
    })
    .catch(() => {
      selectKey.value = [];
      videolistsearch.value.idlist = "";
    });
};
//单删确定
const oneremoveLog = (data) => {
  videolistsearch.value.idlist = data.id;
  removeRequest();
  getDataList();
};
//单删取消
const removeCnacle = () => {
  videolistsearch.value.idlist = "";
};
const reset = () => {
  loginTime.value = "";
  videolistsearch.value = {
    id: null,
    title: "",
    beginTime: null,
    endTime: null,
    idlist: "",
    pageNum: 1,
    pageSize: 20,
  };
  getDataList();
};

// 多选
const handleSelectionChange = (val) => {
  console.log(val);
  let arr = val.map((item) => item.id);
  selectKey.value = arr;
  if (selectKey.value.length > 0) {
    isBatch.value = false;
  } else {
    isBatch.value = true;
  }
};

const onUpload = (file, data) => {
  let formData = new FormData();
  if (file === null) {
    isSend.value = 1;
    return;
  }
  loading.value = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
  formData.append("file", file);

  // let item = {
  //   title: data.title,
  //   position: data.position,
  //   status: data.status,
  //   targetUrl: data.targetUrl,
  //   imgUrl: data.imgUrl,
  // };
  axios({
    url: "https://zfb.bydhy.top/files/img",
    method: "POST",
    headers: {
      "Content-Type": "multipart/form-data",
    },
    processData: false,
    data: formData,
  })
    .then((res) => {
      if (res.data.code === 200) {
        data.imgUrl = res.data.data;
        insertOne(data);
      } else {
        ElMessage.error("图片上传失败");
      }
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

const insertOne = (item) => {
  console.log(item);
  request
    .post("/admin/ad/add", item)
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success("新增成功");
        getDataList();
        loading.value.close();
      }
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });

  setTimeout(() => {
    loading.value.close();
  }, 10000);
};

onMounted(() => {
  // getLogDataList();
  getDataList();
});
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.el-form-item__label {
  font-weight: bold;
}

.el-form {
  display: inline;
}

.activeTag {
  background: #fef0f0;
  border: #fde2e2 1px solid;
  color: #f67777;
}
.el-input {
  position: relative;
  display: inline-block;
  width: 220px;
}
</style>
